package cn.bo.cloud.common.core.utils;


import java.io.File;

public class PathUtils {

    public final static String CLASS_PATH;
    public final static String URL_SEPARATOR = "/";
    public final static String SEPARATOR = File.separator;

    static {
        //获取的是classpath路径，适用于读取resources下资源
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = ClassLoader.getSystemClassLoader();
        }
        java.net.URL url = classLoader.getResource("");
        String ROOT_CLASS_PATH = url.getPath()+"/";
        File rootFile = new File(ROOT_CLASS_PATH);
        String WEB_INFO_DIRECTORY_PATH = rootFile.getParent()+"/";
        File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);
        String SERVLET_CONTEXT_PATH = webInfoDir.getParent();
        CLASS_PATH = SERVLET_CONTEXT_PATH;
    }


    public static String getLocalUserDirPath() {
        String userDir = System.getenv("LOCAL_USER_DIR");
        if (userDir == null) {
            userDir = System.getProperty("user.dir");
        }
        return userDir;
    }


    /**
     * 项目根目录
     */
    public static String getRootPath() {
        return RootPath("");
    }

    /**
     * 自定义追加路径
     */
    public static String getRootPath(String u_path) {
        return RootPath(SEPARATOR + u_path);
    }

    /**
     * 私有处理方法
     */
    private static String RootPath(String u_path) {
        String root_path = "";
        //windows下
        if ("\\".equals(SEPARATOR)) {
            root_path = CLASS_PATH + u_path;
            root_path = root_path.replaceAll("/", "\\\\");
            if (root_path.substring(0, 1).equals("\\")) {
                root_path = root_path.substring(1);
            }
        }
        //linux下  file:/data/www/ROOT/olpv/server-preview-2.0.0-SNAPSHOT.jar!
        if ("/".equals(SEPARATOR)) {
            root_path = CLASS_PATH + u_path;
            root_path = root_path.replaceAll("\\\\", "/");
            if (root_path.startsWith("file:")) {
                root_path = root_path.replaceAll("file:", "");
            }
            if (root_path.endsWith(".jar!") || root_path.endsWith(".jar")) {
                root_path = root_path.substring(0, root_path.lastIndexOf("/"));
            }
        }
        return root_path;
    }

}
